package com.myspring.config;

import org.apache.commons.dbcp2.BasicDataSource;
import org.apache.commons.dbutils.QueryRunner;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;

import javax.sql.DataSource;

/**
 * ClassName: DBConfig
 * Package: com.myspring.config
 * Description:
 *
 * @Author 刘英杰
 * @Create 2025/2/1 16:15
 * @Version 1.0
 */

@Configuration
public class DBConfig {
    /*从配置文件中将值注入到指定的属性中*/

    @Value("${jdbc.driver}")
    private String drive;
    @Value("${jdbc.url}")
    private String url;
    @Value("${jdbc.user}")
    private String user;
    @Value("${jdbc.password}")
    private String password;


    /**
     * //@Bean 用于返回实例的方法上,相当于将方法的返回值定义成一个Bean
     *         Bean的id默认就是方法名
     *         相当于<bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource"></bean>
     * @return
     */
    @Bean("dataSource")
    public DataSource initDataSource() {
        /*新建数据源,给数据库设置数据库连接信息*/
        BasicDataSource basicDataSource = new BasicDataSource();
        basicDataSource.setDriverClassName(drive);
        basicDataSource.setUrl(url);
        basicDataSource.setUsername(user);
        basicDataSource.setPassword(password);
        return basicDataSource;
    }


    /**
     * @Bean("queryRunner") 相当于  <bean class="org.apache.commons.dbutils.QueryRunner" id="queryRunner">
//     * @param dataSource
     * @return
     */
/*    @Bean("queryRunner")
    @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)//将QueryRunner指定成多例,可以防止多线程安全问题,便于事务管理
    public QueryRunner initQueryRunner(DataSource dataSource) {
        return new QueryRunner(dataSource);
    }*/


    /*事务管理:空参构造+传connection*/
    @Bean("queryRunner")
    @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)//将QueryRunner指定成多例,可以防止多线程安全问题,便于事务管理
    public QueryRunner initQueryRunner() {
        return new QueryRunner();
    }
}
